import appConfig from '/src/utils/js/app-config'
import Toast from "/src/components/common/toast";

const URL = `${appConfig.devServe}/phalapi/`
// const URL = `${appConfig.realHost}/phalapi/`
const reqTasks = {}//请求任务
const stringArr = []

/**
 * 创建GET请求
 */
export function getRequest(tag, params, callback) {
    cancelRequest(tag)
    params = params || {}
    if (appConfig.debug) {
        stringArr.length = 0
        stringArr.push(appConfig.realHost)
        stringArr.push('/phalapi/?service=')
        stringArr.push(tag)
        for (let key in params) {
            stringArr.push('&')
            stringArr.push(key)
            stringArr.push('=')
            stringArr.push(params[key])
        }
        console.log(stringArr.join(''))
    }
    params.service = tag
    reqTasks[tag] = uni.request({
        url: URL,
        data: params,
        success: (response) => {
            console.log(response)
            if (response.data.ret !== 200) {
                console.log(response.data.msg)
                if (callback && callback.onFail) {
                    callback.onFail(response.data.msg);
                }
                return
            }
            const {code, msg, info} = response.data.data;
            if (appConfig.debug) {
                console.log(code, msg, info)
            }
            if (code === 700) {
                Toast.show(msg)
                return;
            }
            if (callback) {
                if (typeof callback === 'function') {
                    callback(code, msg, info)
                } else {
                    if (callback.onSucc) {
                        callback.onSucc(code, msg, info)
                    }
                }
            }
        },
        fail: error => {
            Toast.show('网络请求错误')
            console.log(error)
            if (callback && callback.onFail) {
                callback.onFail(error);
            }
        },
        complete: () => {
            reqTasks[tag] = null
            if (callback && callback.onFinish) {
                callback.onFinish();
            }
        }

    })
}

/**
 * 取消请求
 */
export function cancelRequest(tag) {
    if (reqTasks[tag]) {
        reqTasks[tag].abort()//中断请求任务
        reqTasks[tag] = null
        if (appConfig.debug) {
            console.log('取消请求--->' + tag)
        }
    }
}
